/*Rasmus Nielsen*/

#include "i2cmodule.h"

int main(int argc, char **argv){
  initi2c();
  return 0;
}

PyMODINIT_FUNC initi2c(void){
  PyObject *module_methods, *module_dictionary;
  
  module_methods = Py_InitModule("i2c",i2cmethods);
  module_dictionary = PyModule_GetDict(module_methods);
  return;
}

static PyObject *i2c_open(PyObject *self, PyObject *args){
  char *dev_path;
  
  PyArg_ParseTuple(args,"s",&dev_path);
  
  return Py_BuildValue("i",open(dev_path,O_RDWR));
}

static PyObject *i2c_slave(PyObject *self, PyObject *args){
  int i2c_dev, slave;
  
  PyArg_ParseTuple(args,"ii",&i2c_dev,&slave);
  
  return Py_BuildValue("i",ioctl(i2c_dev,I2C_SLAVE,slave));
}

static PyObject *i2c_write(PyObject *self, PyObject *args){
  int i2c_dev, value, adr=-1;
  
  PyArg_ParseTuple(args,"ii|i",&i2c_dev,&value,&adr);
  if (adr<0){
    value=i2c_smbus_write_byte(i2c_dev,value);
  }else{
    value=i2c_smbus_write_byte_data(i2c_dev,adr,value);
  }
  
  return Py_BuildValue("i",value);
}

static PyObject *i2c_read(PyObject *self, PyObject *args){
  int i2c_dev, value, adr=-1;
  
  PyArg_ParseTuple(args,"i|i",&i2c_dev,&adr);
  
  if (adr<0){
    value=i2c_smbus_read_byte(i2c_dev);
  }else{
    value=i2c_smbus_read_byte_data(i2c_dev,adr);
  }
  
  return Py_BuildValue("i",value);
}

static PyObject *i2c_close(PyObject *self, PyObject *args){
  int i2c_dev;
  
  PyArg_ParseTuple(args,"i",&i2c_dev);
  
  return Py_BuildValue("i",close(i2c_dev));
}
